<?php
/**
 * Created by PhpStorm.
 * User: sunyang
 * Date: 2017/1/22
 * Time: 17:38
 */
class UploadLib{
    var $_uploader=null;
    function __construct()
    {
        $this->uploadbase();
    }
    public function uploadbase(){
        static $uploader = null;
        if($uploader === null){
            include_once(ROOTPATH . '/lib/include/uploader.lib.php');
            $uploader = new Uploader;
            $uploader->allowed_type('gif|jpg|jpeg|png'); // 限制文件类型
            $uploader->allowed_size(2097152);
        }
        $this->_uploader = $uploader;
    }
    public function upload_file($file,$to_dir,$to_name=''){
        $this->_uploader->addFile($file);
        if (!$this->_uploader->file_info())
        {
            $arrData = array(
                'status'=>0,
                'error'=>implode(' | ',$this->_uploader->_errors)
            );
            return $arrData;
        }
        if(!$to_name){
            $to_name  = $this->_uploader->random_filename();
        }
        $file_path = $this->_uploader->save( APP_PUBLIC.'/'.$to_dir, $to_name); // 保存到指定目录
        if($file_path){
            $file_name = basename($file_path);
            $arrData = array(
                'url'=>DOMAIN.'/public/'.$to_dir.'/'.$file_name,
                'path'=>'public/'.$to_dir,
                'name'=>$file_name
            );
        }else{
            $arrData = array(
                'status'=>0,
                'error'=>'保存失败'
            );
        }
        return $arrData;
    }
    public function allowed_type($type){
        $this->_uploader->allowed_type($type);
    }
    public function allowed_size($size){
        $this->_uploader->allowed_size($size);
    }
}